//
//  playRequestModel.m
//  SoundPill
//
//  Created by 宋旭东 on 16/2/29.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "playRequestModel.h"
#import "AFNetworking.h"
#import "Player_ShowModel.h"
#import "Comment.h"

@implementation playRequestModel
- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}
- (void)requestNextWork:(playerTableViewController *)player workID:(NSString *)workID
{
    Player_ShowModel *playModel = [Player_ShowModel sharedInstance];
    NSString *showURL = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/show", workID];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *head = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:head forHTTPHeaderField:@"authorization"];
    [manager GET:showURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSDictionary *dataDic = [dic valueForKey:@"data"];
        NSDictionary *linksDic = [dic valueForKey:@"links"];
        [playModel setValuesForKeysWithDictionary:dataDic];
        if ([[dic allKeys] containsObject:@"meta"]) {
            NSDictionary *meta = [dic valueForKey:@"meta"];
            NSString *userAvatar = [meta valueForKey:@"userAvatar"];
            player.locUserAvatar = userAvatar;
//            if (player.playList.count > 0) {
//                [player.playList removeObjectAtIndex:0];
//            }
//            if (player.playList.count == 0 || player.playList == nil) {
//                NSArray *array = [meta valueForKey:@"playlist"];
//                player.playList = [NSMutableArray arrayWithArray:array]
//                ;
//            } else {
//            }
        }
        player.waveform = [linksDic valueForKey:@"waveform"];
        player.workID = workID;
        player.isSelf = NO;
        [player reloadViews:playModel];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)getWaveForm:(playerTableviewHeader *)player workID:(NSString *)workID
{
    NSString *url = player.waveform;
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = [responseObject valueForKey:@"peaks"];
        [player.waveArray removeAllObjects];
        for (NSString *str  in arr) {
            float waveNum = str.floatValue;
            NSString *wave = [NSString stringWithFormat:@"%.2f", waveNum];
            [player.waveArray addObject:wave];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [player refresh];
        });

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [player.waveArray removeAllObjects];
        dispatch_async(dispatch_get_main_queue(), ^{
            [player refresh];
        });

    }];
}

- (void)requestComment:(playerTableviewHeader *)player workID:(NSString *)workID
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/comment/%@/show", workID];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManager stopMonitoring];
        NSMutableDictionary *data = responseObject;
        if (data.count > 0) {
            NSMutableDictionary *bigDic = data[@"data"];
            
            player.commentArray = [NSMutableArray array];
            for (NSDictionary *smallDic in bigDic) {
                Comment *comment = [[Comment alloc] init];
                comment.avatar = smallDic[@"avatar"];
                comment.comment = smallDic[@"content"];
                comment.timeLine = smallDic[@"timeline"];
                [player.commentArray addObject:comment];
            }
            player.commentCount = [[data valueForKey:@"meta"] valueForKey:@"count"];
        } else {
        }
//        [player.bottomBtn changeBtnFrame];
        [player loadLikeCount:player.love_count commentCount:player.commentCount.stringValue];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)uploadComment:(playerTableViewController *)player workid:(NSString *)workid
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/comment/%@/add", workid];
      AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *user_id = [user objectForKey:@"uid"];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:player.commentField.comment.text, @"content", user_id, @"user_id", [NSString stringWithFormat:@"%f", player.header.streamer.currentTime/player.header.duration.floatValue], @"timeline",nil];
    if (player.locUserAvatar && player.locUserAvatar.length > 0) {
        Comment *comment = [[Comment alloc] init];
        comment.avatar = player.locUserAvatar;
        comment.comment = [dic valueForKey:@"content"];
        comment.timeLine = [dic valueForKey:@"timeline"];
        [player.header.rolling createDanmuItem:comment];
    } else {
        [player.header.rolling requestHeadImage:dic];
    }
    if ([player.header.streamer status] == DOUAudioStreamerPaused) {
        [player.header.rolling pauseAnimation];
    }
    
    [manager POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        int comment = player.header.commentCount.intValue + 1;
        NSNumber *commentNum = [NSNumber numberWithInt:comment];
        [player.header loadLikeCount:player.header.love_count commentCount:commentNum.stringValue];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)deleteWork:(playerTableViewController *)player workid:(NSString *)workid
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/delete", workid];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"delete" object:nil];
        if (player.header.streamer.status == DOUAudioStreamerPlaying) {
            [player.header.streamer stop];
        }
        [player backToThePrevious:nil];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)private:(playerTableViewController *)player workid:(NSString *)workid
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/private", workid];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    NSDictionary *dic = nil;
    if (player.isPrivate) {
        dic = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:@"private"];
    } else {
        dic = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:@"private"];
    }
    [manager POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (player.isPrivate == YES) {
            player.isPrivate = NO;
        } else {
            player.isPrivate = YES;
        }
        [player initSheetData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
@end
